<script setup>
import { queryDictionaryDetail } from '@/api/system/dictionary'
const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  visible: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['update:visible', 'create', 'update'])

const formRef = ref()
const formData = reactive({
  dictName: '',
  dictType: '',
  status: 0
})
const formRules = reactive({
  dictName: [{ required: true, trigger: 'blur', message: '请输入字典名称！' }],
  dictType: [{ required: true, trigger: 'blur', message: '请输入字典类型！' }],
  status: [{ required: true, trigger: 'blur', message: '请选择状态！' }]
})
const handleCreate = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      submitBtnLoading.value = true
      const param = {
        dictName: formData.dictName,
        dictType: formData.dictType,
        status: formData.status
      }
      if (!props.id) {
        emit('create', param)
      } else {
        param.id = formData.id
        emit('update', param)
      }
    } else {
      return false
    }
  })
}
const resetForm = () => {
  formRef.value?.resetFields()
  delete(formData.id)
  emit('update:visible')
}
const submitBtnLoading = ref(false)
const editLoading = ref(false)
watch(
  () => props.visible,
  async (newValue, oldValue) => {
    if (newValue) {
      submitBtnLoading.value = false
      const { id } = props
      if (id) {
        editLoading.value = true
        const { data } = await queryDictionaryDetail(id)
        Object.assign(formData, data)
        editLoading.value = false
      }
    }
  }
)
defineExpose({
  submitBtnLoading
})
</script>

<template>
  <el-dialog :close-on-click-modal="false" v-model="visible" :title="id ? '修改字典' : '新增字典'" @close="resetForm" width="60%">
    <el-form v-loading="editLoading" ref="formRef" :model="formData" :rules="formRules" label-width="80px">
      <div class="px-4">
        <el-form-item prop="dictName" label="字典名称">
          <el-input v-model="formData.dictName" placeholder="请输入字典名称" maxlength="20" />
        </el-form-item>
        <el-form-item prop="dictType" label="字典类型">
          <el-input v-model="formData.dictType" placeholder="请输入字典类型" maxlength="20" />
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-radio-group v-model="formData.status" class="ml-4">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="submitBtnLoading" @click="handleCreate">确认</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
